<?php
namespace app\api\controller;

use think\Request;
use app\api\controller\ApiBase;
use app\common\model\UploadFile;

class Upload extends ApiBase
{
    // 上传配置信息
    protected $config = [
        'size' => '2080000', // 上传允许最大字节
        'ext'  => 'jpg,png,gif', // 允许后缀
        'path' => 'upload' . DS . 'image', // 上传目录
        'rule' => 'md5', //上传命名规则
        'type' => 1, // 存储方式 1本地 2阿里云OSS
    ];

    public function _initialize(array $config = [])
    {
        if (empty($this->uid)) {
            return $this->response(201, '无上传权限');
        }

        $this->config = array_merge($this->config, $config);
    }

    /**
     * 上传文件图片
     *
     * @params $file
     * @return boolean|string
     */
    public function uploadImage()
    {
        // 获取表单上传文件
        $file = Request::instance()->file('files');
        switch ($this->config['type'])
        {
            case 1:
                return $this->localUpload($file);
                break;  
            case 2:
                return $this->aliOssUpload($file);
                break;
        }
    }

    /**
     * 上传文件到本地
     *
     * @params $file
     * @return boolean|string
     */
    public function localUpload($file)
    {
        // 上传文件
        $result = $file
            ->rule($this->config['rule'])
            ->validate(['size' => $this->config['size'], 'ext' => $this->config['ext']])
            ->move(ROOT_PATH . $this->config['path']);

        if(empty($result)){
            // 上传失败获取错误信息
            return $this->response(201, $file->getError(), $data);
        }

        // 成功上传后 获取上传信息
        $data['fileName'] = $result->getFilename();
        $data['saveName'] = str_replace('\\', '/', $this->config['path'] . DS . $result->getSaveName());

        // 保存到数据中
        $this->addLog($data['saveName'], $result->md5(), empty($this->uid) ? 0 : $this->uid);
        return $this->response(200, '上传成功', $data);
    }

    /**
     * 上传文件到阿里云OSS
     *
     * @params $file
     * @return boolean|string
     */
    public function aliOssUpload($file)
    {

    }

    /**
     * 删除图片
     *
     * @params $file
     * @return boolean|string
     */
    public function removeImage()
    {
        $imageUrl = Request::instance()->param('key');
        $id       = Request::instance()->param('id');
        $model    = Request::instance()->param('model');
        $clear    = false;

        // 删除数据库中图片路径 
        switch ($model) {
            case 'article':
                $clear = \app\common\model\Article::setImage($id , '');
                break;
            case 'user':
                $clear = \app\common\model\User::setAvatar($id , '');
                break;
            case 'slider':
                $clear = \app\common\model\Slider::setImage($id , '');
                break;
            case 'water':
                $water = json_decode(\app\common\model\Config::getValue('water'), true);
                $water['logo'] = '';
                $clear = \app\common\model\Config::setValue('water', json_encode($water));
                break;
        }

        $paras = str_replace(getDomain(), "", $imageUrl);
        $file = ROOT_PATH . ltrim($paras, '/');

        // 删除物理图片
        if (is_file($file)) {
            unlink($file);
        }

        // 返回信息
        if($clear != false && $file){
            return $this->response(200);
        }else{
           return $this->response(201);
        }
    }

    /**
     * 记录路径到数据库中
     *
     * @params $file
     * @return boolean|string
     */
    public function addLog($path, $hash, $uid)
    {
        $data = [
            'uid' => $uid,
            'hash' => $hash,
            'path' => $path,
            'type' => $this->config['type'],
        ];
        $ojb = new UploadFile();
        $ojb->data($data)->save();
        return $ojb->id;
    }
}
?>